<?php

namespace app\common\model;

use think\Model;

/**
 * Brands
 */
class Brands extends Model
{
    // 表名
    protected $name = 'brands';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 字段类型转换
    protected $type = [
        'establish_time' => 'timestamp:Y-m-d H:i:s',
    ];
    protected $append = [
        'domain_images',
        'domain_image',
        'domain_logo',
        'main_business_text'
    ];
    public function getMainBusinessTextAttr($value, $data)
    {
        return explode(',',$data['main_business']);
    }

    public function getDomainLogoAttr($value,$data)
    {
        return request()->domain().$data['image'];
    }
    public function getDomainImagesAttr($value, $data): array
    {
        $value = isset($data['images']) ? $data['images'] : '';
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        foreach ($value as &$image) {
            $image = request()->domain() . $image;
        }
        return $value;
    }

    public function getDomainImageAttr($value, $data): string
    {
        return request()->domain() . $data['image'];
    }

    protected static function onAfterInsert($model)
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getImagesAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setImagesAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }


    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}
